//
//  ContractorLoginViewController.swift
//  mggz
//
//  Created by 匀视网Mac on 2018/1/3.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Alamofire
import MMDrawerController
class ContractorLoginViewController: BaseLcController {

    @IBOutlet weak var accountTextField: UITextField!
    
    @IBOutlet weak var passwordTextfield: UITextField!
    
    @IBOutlet weak var displayButton: UIButton!
    
    @IBOutlet weak var loginButton: UIButton!
    fileprivate var isDisplay : Bool = true
    
    var currentVasion:String?
    lazy var drawerVc:MMDrawerController = {
        var vc = MMDrawerController()
        vc.showsShadow = false
        return vc
    }()
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupInitUI()
        
        NotificationCenter.default.addObserver(self, selector: #selector(closeDrawable(_:)), name: NSNotification.Name(rawValue: DrawLayoutNotification), object: nil)
        
        
        self.setupCurrentVasionData()
    }
    @objc func closeDrawable(_ sender:Notification){
        print("菜单栏关闭")
        /*guard var operate = sender.object as? NormalClick else{
            return
        }
        self.drawerVc.closeDrawer(animated: false) { (flag) in
            if flag{
                operate()
            }
        }*/
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        accountTextField.resignFirstResponder()
        passwordTextfield.resignFirstResponder()
    }
    func setupInitUI(){
        self.accountTextField.delegate = self
        self.passwordTextfield.delegate = self
        loginButton.layer.cornerRadius = 20
        loginButton.layer.masksToBounds = true
        loginButton.layer.borderWidth = 1
        loginButton.layer.borderColor = colorWith255RGB(16, g: 142, b: 233).cgColor
    }
    @IBAction func forgetPwdClick(_ sender: Any) {
        QWTextonlyHud("请前往PC端找回密码", target: self.view)
    
    }
    @IBAction func displayClick(_ sender: Any) {
        if isDisplay == true {
            isDisplay = false
            passwordTextfield.isSecureTextEntry = false
            displayButton.setImage(UIImage.init(named: "login_openEye"), for: .normal)
        }else{
            isDisplay = true
            passwordTextfield.isSecureTextEntry = true
            displayButton.setImage(UIImage.init(named: "login_closeEye"), for: .normal)
        }
        
        
    }
    
    
    
    @IBAction func goBackClick(_ sender: Any) {
        self.dismiss(animated: true) {
            
        }
    }
    
    
    func loginLoad(_ username:String,password password:String){
        
        QWTextWithStatusHud("正在登录...", target: self.view)
        LCLoginNetWork.login(username:username, password: password) { (response) in
            if response.success {
                //WWEndLoading()
                QWHudDiss(self.view)
                
                
                (UIApplication.shared.delegate as! AppDelegate).setTags(WWUser.sharedInstance.accountId)
                            /*RemoteNotificationModel.registerClient({ (response) in
                                    if response.success {
                                        print("注册客户端推送ID成功")
                                    }
                                    else {
                                        print("注册客户端推送ID失败")
                                    }
                                })*/
                ContractorName = username
                ContractorPass = password
                LoginType = 2
                HttpRequestImpl.registDevice("", _jpushID: JPUSHService.registrationID())
                
                
                let main = LCMainViewController(nibName: "LCMainViewController", bundle: nil)
                let introVC = MainNavigationController.init(rootViewController: main)
                //let left = LeftViewController(nibName: "LeftViewController", bundle: nil)
                let lcMine = LCMineViewController(nibName: "LCMineViewController", bundle: nil)
                // let letNav = UINavigationController.init(rootViewController: lcMine)
                let leftNav = MainNavigationController.init(rootViewController: lcMine)
                
                //var drawerVc = MMDrawerController()
                //self.drawerVc = MMDrawerController(center: introVC, leftDrawerViewController: leftNav)
                self.drawerVc.centerViewController = introVC
                self.drawerVc.leftDrawerViewController = leftNav
                
                self.drawerVc.maximumLeftDrawerWidth = SCREEN_WIDTH * 0.8
                
                
                
                // drawerVc.openDrawerGestureModeMask = .all
                // drawerVc.closeDrawerGestureModeMask = .all
                
                self.drawerVc.setDrawerVisualStateBlock { (drawerController, drawerSlide, percentVisible) in
                    var sideDrawerController : UIViewController?
                    if drawerSlide == MMDrawerSide.left{
                        sideDrawerController = drawerController?.leftDrawerViewController
                    }
                    if drawerSlide == MMDrawerSide.right{
                        sideDrawerController = drawerController?.rightDrawerViewController
                    }
                    sideDrawerController?.view.alpha = percentVisible
                }
                UIApplication.shared.delegate?.window!?.rootViewController = self.drawerVc
            }
            else {
                QWHudDiss(self.view)
                QWTextonlyHud(response.message, target: self.view)
            }
        }
    }
    
    
    @IBAction func loginButtonClick(_ sender: Any) {
        guard let username = self.accountTextField.text, username.count > 0 else {
            WWError("用户名为空")
            return
        }
        guard let password = self.passwordTextfield.text, password.count > 0 else {
            WWError("密码为空！")
            return
        }
        self.loginLoad(username, password: password)
    }
    
    
    fileprivate func setupCurrentVasionData(){
        let infoDictionary = Bundle.main.infoDictionary
        if let infoDictionary = infoDictionary {
            self.currentVasion = (infoDictionary["CFBundleShortVersionString"] as! String)
            self.checkAppVasionData()
        }
    }
    
    fileprivate func checkAppVasionData(){
        QWTextWithStatusHud("正在检测...", target: self.view)
        Alamofire.request(CheckNewVasionUrl, method: .get, parameters: nil, headers: nil).responseJSON { (response) in
            QWHudDiss(self.view)
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: Any] {
                    
                    guard let vasionCode :String = dict["VersionCode"] as? String else{
                        return
                    }
                    guard let vasionIsForce : Bool = dict["IsForce"] as? Bool else{
                        return
                    }
                    guard let vasionNum : Int = dict["VersionNum"] as? Int else{
                        return
                    }
                    guard let appPath : String = dict["AppPath"] as? String else{
                        return
                    }
                    if self.currentVasion != vasionCode && vasionNum > 0{
                        if vasionIsForce == true{
                            let alert = UIAlertController(title: "太公民工已更新到最新版本，请前往App Store商店下载，为你带来的不便，敬请谅解！", message: "", preferredStyle: .alert)
                            let gotoAppstore = UIAlertAction(title: "前往下载", style: .default, handler: { (action) in
                                let url = NSURL(string: appPath)
                                UIApplication.shared.openURL(url! as URL)
                                self.present(alert, animated: true, completion: {
                                    
                                })
                            })
                            alert.addAction(gotoAppstore)
                            self.present(alert, animated: true, completion: {
                                
                            })
                        }else{
                            let alert = UIAlertController(title: "太公民工已更新到最新版本，请前往App Store商店下载，为你带来的不便，敬请谅解！", message: "", preferredStyle: .alert)
                            let gotoAppstore = UIAlertAction(title: "前往下载", style: .default, handler: { (action) in
                                let url = NSURL(string: appPath)
                                UIApplication.shared.openURL(url! as URL)
                                self.present(alert, animated: true, completion: {
                                    
                                })
                            })
                            let refuseApp = UIAlertAction(title: "残忍拒绝", style: .cancel, handler: { (action) in
                                
                            })
                            refuseApp.setValue(UIColor.gray, forKey: "titleTextColor")
                            alert.addAction(gotoAppstore)
                            alert.addAction(refuseApp)
                            self.present(alert, animated: true, completion: {
                                
                            })
                        }
                    }else{
                        if LoginType == 2{
                            self.loginLoad(ContractorName ?? "", password: ContractorPass ?? "")
                        }
                    }
                }else{
                    
                }
            }else{
                
            }
        }
    }
    
}
extension ContractorLoginViewController : UITextFieldDelegate{
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        accountTextField.resignFirstResponder()
        passwordTextfield.resignFirstResponder()
        return true
    }
}
